package com.egao.common.core.security;

import com.egao.common.system.entity.Role;
import com.egao.common.system.entity.User;
import com.egao.common.system.service.RoleService;
import com.egao.common.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户登录验证Service
 * Created by wangfan on 2020-03-23 18:45
 */
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getUserByUsername(new User(username));
        if (user == null) throw new UsernameNotFoundException("Username Not Found");
        if(!user.getState().equals("0")){ throw new UsernameNotFoundException("账号已冻结"); }
        Role role = new Role();
        role.setUserId(user.getUserId());
        List<Role> roleList = roleService.list(role);
        List<Integer> roleIds = new ArrayList<Integer>();
        if(roleList !=null && roleList.size()>0) {
            for(Role r: roleList) {
                roleIds.add(r.getRoleId());
            }
        }
        user.setRoles(roleService.list(role));
        user.setRoleIds(roleIds);
        return userService.selectUserAuth(user);
    }

}